const db = require("../db");

exports.getCates = (req, res) => {
    const sql = 'select * from article_cate where is_delete=0 ';
    db.query(sql, (err, data) => {
        if (err) return res.cs(err);
        // 2. 执行 SQL 语句成功
        res.send({
            status: 0,
            message: '获取文章分类列表成功！',
            data
        })
    })
};

exports.addCates = (req, res) => {
    const selSql = 'select * from article_cate where name = ? or alias = ?'; // 定义查询sql语句
    db.query(selSql, [req.body.name, req.body.alias], (err, data) => { // 执行语句
        if (err) return res.cs(err);
        if (data.length >= 1) return res.cs('分类别名或者分类名称被占用,请重新再试'); // 判断查询数据
        const addSql = 'insert into article_cate set ?';
        db.query(addSql, req.body, (err, data) => {
            if (err) return res.cs(err);
            if (data.affectedRows === 0) return res.cs('添加失败');
            res.cs('添加成功', 0);
        })
    })
};

exports.delCates = (req, res) => {
    const upSql = 'update article_cate set is_delete=1 where Id = ?';
    db.query(upSql, req.params.id, (err, data) => {
        if (err) return res.cs(err);
        if (data.affectedRows === 0) return res.cs('删除失败');
        res.cs('删除成功',0)
    })
}

exports.Catesid = (req, res) => {
    const sql = `select * from article_cate where id=?`;
    db.query(sql, req.params.id, (err, data) => {
        if (err) return res.cs(err);
        if (data.length !== 1) return res.cs('没有该数据');
        res.send({
            status: 0,
            msg: '查询成功',
            data
        });
    })
};

exports.upCates = (req, res) => {
    const selSql = 'select * from article_cate where Id != ? and (name = ? or alias = ?)';
    db.query(selSql, [req.body.id, req.body.name, req.body.alias], (err, data) => {
        if (err) return res.cs(err);
        if (data.length >= 1) return res.cs('查询失败');
        const upSql = 'update article_cate set ? where Id=?';
        db.query(upSql, [req.body, req.body.Id], (err, data) => {
            // 执行 SQL 语句失败
            if (err) return res.cs(err)
          
            // SQL 语句执行成功，但是影响行数不等于 1
            if (data.affectedRows !== 1) return res.cs('更新文章分类失败！')
          
            // 更新文章分类成功
            res.cs('更新文章分类成功！', 0)
          })
    })
}